package com.bonana.bozone.controller;

import com.alibaba.fastjson.JSON;
import com.bonana.bozone.form.LoginForm;
import com.bonana.core.entity.CoreUser;
import com.bonana.core.entity.CoreUserProfile;
import com.bonana.core.entity.mybatis.UserAlbum;
import com.bonana.core.form.UserSingleFieldFrom;
import com.bonana.core.result.Response;
import com.bonana.core.result.ResponseCode;
import com.bonana.core.services.AlbumService;
import com.bonana.core.services.BoBoService;
import com.bonana.core.vo.*;
import com.bonana.utils.Assert;
import com.bonana.utils.ConvertUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by justin on 15/8/14.
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private BoBoService boBoService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    ServletContext servletContext;

    @Autowired
    private HttpSession session;

    @Autowired
    private AlbumService albumService;

    private int getCurUid() {
        int uid = 0;
        if (session.getAttribute("session.uid") != null) {
            uid = ConvertUtils.toInteger(session.getAttribute("session.uid"));
        }
        return uid;
    }

    @RequestMapping(value = "dynamicPwd")
    @ResponseBody
    public Response dynamicPwd(@RequestParam(required = true) String username) {
        Assert.notNull(username);
        boBoService.updateDynamicPwd(username);
        return new Response(ResponseCode.SUCC);
    }

    @RequestMapping(value = "setPwd")
    @ResponseBody
    public Response setPwd(String username, String dPwd, String pwd) {
        Assert.notNull(username);
        int uid = boBoService.resetPwd(username, pwd, dPwd);
        if (uid > 0) {
            session.setAttribute("session.uid" , uid);
            session.setAttribute("session.username", username);
            session.setAttribute("session.name", username);
            return new Response(ResponseCode.SUCC);
        } else {
            return new Response(ResponseCode.ERROR);
        }
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public UserLoginVO login(LoginForm loginForm) {
        UserLoginVO userLoginVO = boBoService.login(loginForm.getUsername(), loginForm.getPassword(), request.getRemoteAddr());
        if(userLoginVO.getResult().getResultCode() == 0) {
            session.setAttribute("session.uid" , userLoginVO.getUser().getUid());
            session.setAttribute("session.username", userLoginVO.getUser().getUsername());
            session.setAttribute("session.name", userLoginVO.getUser().getUsername());
        }
        return userLoginVO;
    }

    @RequestMapping(value = "avatar/{uid}", method = RequestMethod.POST)
    @ResponseBody
    public AvatarVo uploadAvatar(@PathVariable int uid, MultipartFile avatarFile) {
        return boBoService.updateUserAvatar(uid, avatarFile);
    }

    @RequestMapping(value = "saveProfile", method = RequestMethod.POST)
    @ResponseBody
    public Response saveUserProfile(UserSingleFieldFrom fieldFrom) {
        if (boBoService.updateSingleField(getCurUid() , fieldFrom) > 0) {
            return new Response(ResponseCode.SUCC);
        } else {
            return new Response(ResponseCode.ERROR);
        }
    }

    @RequestMapping(value = "{uid}", method = RequestMethod.GET)
    public String BoHome(@PathVariable int uid, Model model) {
        Integer fromId = 0;
        if (session.getAttribute("session.uid") != null) {
            fromId = ConvertUtils.toInteger(session.getAttribute("session.uid"));
        }

        CoreUser userinfo = boBoService.getBoboById(uid);
        if (userinfo.getIsRobot() == 0) {
            return "redirect:/";
        }

        UserCardVO userInfo = boBoService.queryUserCardByUid(uid, fromId, (long) 0);
        model.addAttribute("user", userInfo.getUserProfile());

        OperStatusVO status = boBoService.getRelation(uid, fromId);
        model.addAttribute("op", status);

        List<BoPlanVo> plan = boBoService.getBoboPlanDisplay(uid);
        model.addAttribute("plan", plan);

        return "user/card";
    }

    @RequestMapping(value="getBoboer", method = RequestMethod.POST)
    @ResponseBody
    public PageInfo getBoboer(Integer pgNum, Integer pgSize, String orderType, @RequestParam(required = false) String query) {
        List<CoreUserProfile> list = boBoService.getBobos(pgNum, pgSize, orderType, query, null, 0);
        return new PageInfo(list);
    }

    @RequestMapping(value="")
    public String BoList() {
        return "user/list";
    }

    @RequestMapping(value="edit")
    public String editProfile(Model model) {
        if(getCurUid()>0) {
            CoreUserProfile profile = boBoService.queryUserProfileByUid(getCurUid(), (long) 0);
            CoreUser user = boBoService.getBoboById(getCurUid());
            model.addAttribute("profile", profile);
            model.addAttribute("isBoer", user.getIsRobot());
            return "user/edit";
        } else {
            return "redirect:/";
        }
    }

    @RequestMapping(value = "{uid}/card", method = RequestMethod.GET)
    @ResponseBody
    public UserCardVO getUserCard(@PathVariable int uid,
                                  @RequestParam(required = true) int fromUid,
                                  @RequestParam(required = false, defaultValue = "0") Long ts) {
        return boBoService.queryUserCardByUid(uid, fromUid, ts);
    }

    @RequestMapping(value = "album" , method = RequestMethod.POST)
    @ResponseBody
    public UserAlbum updateAlbum(UserAlbum album) {
        Integer uid = 0;
        if (session.getAttribute("session.uid") != null) {
            uid = ConvertUtils.toInteger(session.getAttribute("session.uid"));
            album.setUserId(uid);
            if (album.getAlbumId()!=0) {
                albumService.RemoveAlbumById(album.getAlbumId());
            } else {
                album.setCreateTime(new Date());
                int ret = albumService.AddAlbum(album);
                album.setAlbumId(ret);
            }
        }
        return album;
    }

    @RequestMapping(value = "getUserAlbum" , method = RequestMethod.POST)
    @ResponseBody
    public PageInfo getUserAlbum(Integer uid, int pgSize, int pgNum) {
        List<UserAlbum> albums = albumService.getUserAlbum(uid,pgSize,pgNum);
        return new PageInfo(albums);
    }

    @RequestMapping(value = "getHotUsers" , method = RequestMethod.POST)
    @ResponseBody
    public List getHotUsers(@RequestParam(required = false, defaultValue = "6") Integer size) {
        return boBoService.getHotBobos(size);
    }

    @RequestMapping(value = "getNewestUsers" , method = RequestMethod.POST)
    @ResponseBody
    public List getNewestUsers(@RequestParam(required = false, defaultValue = "6") Integer size) {
        return boBoService.getNewestBobos(size);
    }

    @RequestMapping(value = "followUser")
    @ResponseBody
    public Response followUser(Integer uid) {
        int fromUid = getCurUid();
        if (fromUid>0) {
            if (boBoService.addFollow(fromUid, uid)>0) {
                return new Response(ResponseCode.SUCC);
            }
        }
        return new Response(ResponseCode.USER_NOT_LOGIN);
    }

    @RequestMapping(value = "unFollowUser")
    @ResponseBody
    public Response unFollowUser(Integer uid) {
        int fromUid = getCurUid();
        if (fromUid>0) {
            boBoService.unFollow(fromUid, uid);
        }
        return new Response(ResponseCode.SUCC);
    }

    @RequestMapping(value = "FavUser")
    @ResponseBody
    public Response FavUser(Integer uid) {
        int fromUid = getCurUid();
        if (fromUid>0) {
            if (boBoService.addFavor(fromUid, uid)>0) {
                return new Response(ResponseCode.SUCC);
            }
            return new Response(ResponseCode.ERROR);
        }
        return new Response(ResponseCode.USER_NOT_LOGIN);
    }

    @RequestMapping(value = "unFavUser")
    @ResponseBody
    public Response unFavUser(Integer uid) {
        int fromUid = getCurUid();
        if (fromUid>0) {
            boBoService.unFavor(fromUid, uid);
        }
        return new Response(ResponseCode.SUCC);
    }

    @RequestMapping(value = "addComment")
    @ResponseBody
    public Response addComment(Integer boId, Integer parrentId, String content) {
        int uid = getCurUid();
        if (uid > 0) {
            boBoService.addComment(boId, uid, parrentId, content);
            return new Response(ResponseCode.SUCC);
        } else {
            return new Response(ResponseCode.ERROR);
        }
    }

    @RequestMapping(value = "getBoComments")
    @ResponseBody
    public PageInfo getBoComments(Integer boId, Integer pgNum, Integer pgSize) {
        List<BoCommentVo> comments = boBoService.getBoComments(boId, pgNum, pgSize);
        return new PageInfo(comments);
    }
}
